const express = require('express')
const articleCate = express.Router()
const db = require('../db')
const { validation } = require('../utils')
const Joi = require('joi')

// 新增和修改分类
const articleCate_schema = Joi.object({
    id: Joi.number().error(new Error('id不规范')),
    name: Joi.string().required().error(new Error('分类名称不能为空')),
    alias: Joi.string().required().error(new Error('分类类别不能为空')),
})
articleCate.post('/articleCate', validation(articleCate_schema), (req, res) => {
    db.query('INSERT INTO ev_article_cate set ? ON DUPLICATE KEY UPDATE ?', [req.body, req.body], (err, result) => {
        if (err) return res.cc(err)
        res.send({ code: 200, msg: '成功', data: req.body })
    });
})

// 分类列表
articleCate.get('/articleCate', (req, res) => {
    const sql = req.query.id ?
        'select * from ev_article_cate where id = ? and isdel != 1' :
        'select * from ev_article_cate where isdel != 1 order by id desc limit 10 offset 0'
    db.query(sql, req.query.id, (err, result) => {
        if (err) return res.cc(err)
        res.send({ code: 200, msg: '成功', data: result })
    })
})

// 删除分类
const articleCate_del_schema = Joi.object({
    id: Joi.number().required().error(new Error('id错误')),
})
articleCate.delete('/articleCate',validation(articleCate_del_schema), (req, res) => {
    const id = req.query.id
    db.query('update ev_article_cate set ? where id = ?', [{ isdel: 1 }, id], (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('没有该id数据')
        res.send({ code: 200, msg: '成功', data: { id } })
    })
})


// commonjs 导出模块
module.exports = articleCate